package com.hangsu.train.netty;

import com.hangsu.train.heatbeat.Server;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class NettyServer implements InitializingBean{

    @Autowired
    private WSServerInitialzer wsServerInitialzer;

    public void startServer() {
        log.info("NETTY SERVER START ... ");
        //创建两个线程组，用于接收客户端的请求任务,创建两个线程组是因为netty采用的是反应器设计模式
        //反应器设计模式中bossGroup线程组用于接收
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //workerGroup线程组用于处理任务
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        //创建netty的启动类
        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new LoggingHandler(LogLevel.INFO));

            bootstrap.childHandler(wsServerInitialzer);
            Channel  channel = bootstrap.bind(10090).sync().channel();

            channel.closeFuture().sync();//关闭通道
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //优雅退出
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    @Override
    public void afterPropertiesSet() {
        Server.getInstance().start();
        log.info("HEARTBEAT SERVER START SUCCESS");
        new Thread(() -> {
            try {
                this.startServer();
                log.info("NETTY SERVER START SUCCESS");
            } catch (Exception e) {
                log.info("NETTY服务启动出错:{}", e.getMessage());
            }
        }).start();
    }
}
